package com.leo.m1802.d05;

/**
 * Created by LEO on 2018/2/5.
 */
public class KMP {
    int[] getNext(String a){
        int[] next = new int[a.length()];
        next[0] = -1;
        int k = -1;
        int j = 0;
        while (j < a.length()){
            if (k==-1 || a.charAt(j) == a.charAt(k)){
                k++;
                j++;
                next[j]=k;
            }else{
                k = next[k];
            }
        }
        return next;
    }

    int kmpSearch(String s, String p){
        int[] next = getNext(p);
        int i = 0,j = 0;
        while (i<s.length() && j<p.length()){
            if (j==-1 || s.charAt(i) == p.charAt(j)){
                i++;
                j++;
            }else {
                j = next[j];
            }
        }
        if (j == p.length()){
            return i-j;
        }else {
            return -1;
        }
    }
}
